package com.kingtop.base.action;

import com.kingtop.base.model.BaseUser;
import com.kingtop.base.service.IBaseUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.kingtop.action.BaseAction;
import org.kingtop.action.StatusCodeEnum;
import org.kingtop.action.annotation.CurrentUser;
import org.kingtop.cache.IRedisTemplate;
import org.kingtop.cache.app.UserCacheUtil;
import org.kingtop.model.IUserPO;
import org.kingtop.shiro.exception.ShiroExceptionEnum;
import org.kingtop.shiro.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
public class BaseUserAction extends BaseAction{
	
	@Autowired
	private IBaseUserService baseUserService;
	@Autowired
	private IRedisTemplate redisTemplate;

	@RequestMapping(value = {"index","/"})
	public String index(@CurrentUser BaseUser user, Model model){
		model.addAttribute("user", user);
		return "index";
	}

	@RequestMapping(value = "/login", method=RequestMethod.POST)
	public String showLoginForm(HttpServletRequest req, Model model) {
		String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
		String error = ShiroExceptionEnum.getByClassName(exceptionClassName).orElse(ShiroExceptionEnum.DEFAULT_EXCEPTION).getMessage();
		model.addAttribute("userMessage", error);
		model.addAttribute("username", req.getParameter("username"));
		return "login";
	}
	
	@RequestMapping(value = "/login", method=RequestMethod.GET)
	public String login(HttpServletRequest req){
		return "login";
	}

	@RequestMapping(value = "tokenlogin", method = RequestMethod.POST)
	@ResponseBody
	public String tokenLogin(String username, String password){
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            SecurityUtils.getSubject().login(token);
            // TODO 这边还有个问题，如果token的过期时间和session的过期时间必须一致
            int expire = 3600 * 1000;
            Object jwtToken = TokenUtil.createJWT(SecurityUtils.getSubject().getSession().getId().toString(), null, token.getPrincipal().toString(), new Date(), expire, null);
            return this.getJson(StatusCodeEnum.OK, jwtToken);
        } catch (Exception e) {
            Object error = ShiroExceptionEnum.getByClassName(e.getClass().getName()).orElse(ShiroExceptionEnum.DEFAULT_EXCEPTION).getMessage();
            return this.getJson(StatusCodeEnum.UNAUTHORIZED, error);
        }
    }

}